﻿using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace vueweb
{
	public class CommonDataProtection
	{
		private IDataProtector _dataProtector;

		public CommonDataProtection(string purpose)
		{			
			_dataProtector = Singleton<IServiceProvider>.Instance.GetDataProtector(purpose);
		}
		public string Protect(string data)
		{
			if (_dataProtector == null)
			{
				throw new ArgumentNullException(nameof(_dataProtector));
			}
			if (string.IsNullOrEmpty(data))
			{
				return data;
			}

			var userData = Encoding.UTF8.GetBytes(data);

			var protectedData = _dataProtector.Protect(userData);
			return Convert.ToBase64String(protectedData).TrimEnd('=');
		}

		public string Unprotect(string protectedText)
		{
			try
			{
				if (string.IsNullOrEmpty(protectedText))
				{
					return string.Empty;
				}

				var protectedData = Convert.FromBase64String(Pad(protectedText));
				if (protectedData == null)
				{
					return string.Empty;
				}

				var userData = _dataProtector.Unprotect(protectedData);
				if (userData == null)
				{
					return string.Empty;
				}

				return Encoding.UTF8.GetString(userData);
			}
			catch (Exception ex)
			{
				// Log the exception, but do not leak other information
				//logger.ErrorUnprotectingSessionCookie(ex);
				return string.Empty;
			}
		}

		private static string Pad(string text)
		{
			var padding = 3 - ((text.Length + 3) % 4);
			if (padding == 0)
			{
				return text;
			}
			return text + new string('=', padding);
		}
	}
}
